using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace XMLTest
{
	[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
	public class AppSettings
	{
		// the info
		private string hostName;
		private string dbName;
		private string userName;
		private string password;
	
		[System.Xml.Serialization.XmlElementAttribute()]
		public string HostName
		{
			get { return hostName; }
			set { hostName = value; }
		}
		[System.Xml.Serialization.XmlElementAttribute()]
		public string DbName
		{
			get { return dbName; }
			set { dbName = value; }
		}
		[System.Xml.Serialization.XmlElementAttribute()]
		public string UserName
		{
			get { return userName; }
			set { userName = value; }
		}
		[System.Xml.Serialization.XmlElementAttribute()]
		public string Password
		{
			get { return password; }
			set { password = value; }
		}
		
		public void MakeDefault ()
		{
			hostName = "10.10.13.1";
			dbName = "XE";
			userName = "Radu";
			password = "panamea";
		}
	}
	
	public class SerializeXML
	{
		// default settings file
		private string settingsFileName = @"/mnt/hdd1/work/tests/c_sharp/XMLTest/XMLTest/settings2.xml";
		
		public void WriteToFile()
		{
			AppSettings appSett = new AppSettings ();
			appSett.MakeDefault ();
			
			TextWriter tr = new StreamWriter (settingsFileName);
			XmlSerializer sr = new XmlSerializer (typeof (AppSettings));
			sr.Serialize (tr, appSett);
			tr.Close ();
			
			Console.WriteLine ("SerializeXML > WriteToFile ()");
		}
		
		public void ReadFromFile()
		{
			AppSettings appSett = new AppSettings ();
			
			FileStream f;
			
			try {
				f = new FileStream(settingsFileName, FileMode.Open);
				XmlSerializer sr = new XmlSerializer (typeof (AppSettings));
				appSett = (AppSettings) sr.Deserialize (f);
			} catch (FileNotFoundException ex) {
				// fisierul nu exista, incarcam setarile default
				appSett.MakeDefault ();
			}
			
			Console.WriteLine (appSett.HostName);
			Console.WriteLine (appSett.DbName);
			Console.WriteLine (appSett.UserName);
			Console.WriteLine (appSett.Password);
			
			Console.WriteLine ("SerializeXML > ReadFromFile ()");
		}
	}
}
